<?php
/*
 * @Author: CHINAKAIYUAN<sunkaiyuan@namenode.cn>
 * @Date: 2022-02-04 16:53:56
 * @LastEditTime: 2023-09-22 14:34:48
 * @LastEditors: 孙开源 && sunkaiyuan@namenode.cn
 * @Description: 加料单
 */

namespace App\Http\Services\Finance;


use App\Http\Services\Service;

use App\Repositories\FinanceVoucherDetailsRepository;
use App\Repositories\FinanceVoucherRepository;

/**
 * @property FinanceVoucherRepository $repository
 * @property FinanceVoucherDetailsRepository $detail
 */
class VoucherService extends Service
    {

    public function boot(

        FinanceVoucherRepository $repository,
        FinanceVoucherDetailsRepository $detail,

    ) {
        $this->repository = $repository;
        $this->detail     = $detail;
        }

    public function info()
        {
        // DB::enableQueryLog();
        $data = $this->repository->withTrashed()->condition(request())->getOne();
        // dd(DB::getQueryLog());

        return $data;
        }

    public function list()
        {
        $data = $this->detail->withTrashed()
            ->condition(request())
            ->orderBy("created_at", 'desc')
            ->orderBy("main_id")
            ->getGrid();
        return $data;
        }
    protected function save()
        {
        $request = request();

        return $this->repository->CreateVoucher($request->billdate, 1, array_map(function ($v)
            {
            return $this->repository->mergeVoucher($v['subject_id'], $v['summary'], $v['debit_amount'], $v['credit_amount'], $v, $v['id']);
            }, $request->details), null, $request->id);
        }
    private function getVoucherIds()
        {
        return $this->detail->whereIn("id", $this->getRequestIds())->withTrashed()->pluck("main_id");
        }
    protected function delete()
        {
        return $this->repository->whereIn("id", $this->getVoucherIds())->withTrashed()->get()->filter(function ($model)
            {
            //删除单据明细 
            $this->repository->RemoveVoucher($model);
            });
        }
    protected function audit()
        {
        return $this->repository->whereIn("id", $this->getVoucherIds())->withTrashed()->get()->filter(function ($model)
            {
            if ($model->status_id != 0) {
                fail("凭证已经{$model->status->name}，无法审核");
                }
            //审核单据 
            return $this->repository->auditVoucher($model);
            });
        }
    protected function noaudit()
        {
        $this->repository->whereIn("id", $this->getVoucherIds())->withTrashed()->get()->filter(function ($model)
            {
            //审核单据
            if ($model->status_id != 1) {
                fail("凭证已经{$model->status->name}，无法作废");
                }
            $this->repository->auditVoucher($model, false);
            $model->refresh();
            if ($model->status_id != -1)
                return $this->repository->RemoveVoucher($model);
            });
        }
    }